package com.bw.config;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtils {


    /**
     * @param list      数据
     * @param fileName  文件名
     * @param sheetName sheet页的名字
     * @param response  返回给客户端（浏览器）
     */
    public static void exportExcel(List list, String fileName, String sheetName, HttpServletResponse response) {
        try {
            if (CollectionUtil.isEmpty(list)) {
                throw new RuntimeException("导出的数据不能为空");
            }
            //告诉浏览器返回的是 Excel
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //告诉浏览器编码规则
            response.setCharacterEncoding("utf-8");
            //文件名进行编码
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            //响应头加文件名信息
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //写入到response的输出流
            EasyExcel.write(response.getOutputStream(), list.get(0).getClass()).sheet(sheetName).doWrite(list);
        } catch (Exception e) {
            System.out.println("导出Excel失败:" + e.getMessage());
        }

    }
}
